updateVariantHelper
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: updateExistingVariantDocument
Author: Domenico Cerone Creation Date: 09/10/2025
Last Reviewer: Domenico Cerone
Trigger: Helper function (called by updateVariantProduct)
Purpose: Updates an existing document in the 'Variants' Firestore collection using updated mapped JSON data. This function handles complete field refresh and tag regeneration while maintaining workflow fields unchanged.
Detailed Functionalityโ
This helper function performs comprehensive updates to existing Variants documents with complete tag regeneration using thread-safe utilities.
1. EXISTING DOCUMENT LOADINGโ
- Receives
variantRefas document ID parameter - Loads existing document from 'Variants' collection
- If NOT EXISTS โ error (does not create new documents)
- If EXISTS โ proceeds with update (STEP 2)
2. FIELD UPDATES AND TAG REGENERATIONโ
- Updates only fields that come from mapped JSON
- COMPLETELY REGENERATES TAGS (like populateVariantFromSku):
- list_size_color_tags with frameColor and size tag IDs
- Searches/creates tags in Tags collection using tagUtils
- Thread-safe to avoid duplicates
- Maintains all existing workflow fields unchanged
- Updates lastUpdate with current timestamp
Fields Updated from Mapped JSONโ
Base Variant Fields:
eanCodeโ eanCodeframeColorโ frameColorlensesColorโ lensesColorglassesNameโ glassesNamemainBrandRefโ brand ID (searches/creates in MainBrands collection)upcCodeโ upcCodeposterโ posterposter2โ poster2poster3โ poster3poster4โ poster4
Boolean Fields:
isADVโ isADV (converted from "YES"/"NO" to boolean)
Timestamp Fields:
lastUpdateโ current timestampskuReleaseDateโ skuReleaseDate (if present)skuEndDateโ skuEndDate (if present)advStartDateโ advStartDate (if present)advEndDateโ advEndDate (if present)
Size Object (all fields as strings):
size.bridgeโ bridgesize.frameWidthโ frameWidthsize.lensHeightโ lensHeightsize.lensWidthโ lensWidthsize.sizeโ sizesize.templeLengthโ templeLengthsize.frontHeightโ frontHeightsize.hingeToHingeโ hingeToHingesize.lensCircumferenceโ lensCircumferencesize.lensAngleโ lensAnglesize.phantoscopicAngleโ phantoscopicAngle
Special Arrays (regenerated from mapped JSON):
list_size_color_tagsโ [frameColor tag ID, size tag ID] (searches/creates in Tags collection)list_imagesโ list_images (array of objects with view and url)
Fields Maintained Unchangedโ
All workflow and configuration fields remain unchanged:
skuModel(primary identifier)assignedTo,assignmentDate,dataTakenbatch,productRef,catalogOrdersRef,prioritiesModelingloadingId,mainModel,modelPriority,modelViewerUrlmodify_model(complete object)posterNoBackground,primaryFrameColorHex,primaryLensesColorHexpriority,refLogVariant,secondaryFrameColorHex,secondaryLensesColorHexstatus,templeColorurlDE,urlES,urlFR,urlGlobal,urlGlobalComplete, etc.variantCode,list_notes
Tag Creation Functionsโ
The function uses specialized thread-safe tag creation functions:
Frame Color and Size Tags:
findOrCreateTag()- Creates/finds tags with specified type and group- Frame Color: type="frameColor", group="Frame Color", groupOrder=11
- Size: type="size", group="Size", groupOrder=10
Brand Management:
findOrCreateMainBrand()- Creates/finds brands in MainBrands collection
Input Parametersโ
Function Signature:
async function updateExistingVariantDocument(variantRef, mappedJsonData, requestId)
Parameters:
variantRef(string, required): ID of the Variants document to updatemappedJsonData(Object, required): Updated mapped JSON datarequestId(string, required): Request ID for logging
Expected mappedJsonData Structure:
This data comes from the main function after processing the CatalogOrder document and downloading/mapping fresh data from Safilo APIs:
{
"mapped_data": {
"eanCode": "0762753916013",
"frameColor": "BLACK",
"lensesColor": "GREY GRADIENT",
"glassesName": "BOSS 1234/S",
"mainBrandRef": "BOSS EYEWEAR",
"upcCode": "762753916013",
"poster": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg",
"poster2": "https://firebasestorage.googleapis.com/v0/b/.../view_07.jpg",
"poster3": "https://firebasestorage.googleapis.com/v0/b/.../view_02.jpg",
"poster4": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg",
"isADV": "YES",
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12",
"list_images": [
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg"
}
],
"skuReleaseDate": 1640995200000,
"skuEndDate": 1672531200000,
"advStartDate": 1640995200000,
"advEndDate": 1672531200000
}
}
Output (Success)โ
{
"success": true,
"operation": "update",
"documentId": "existing_variant_id",
"skuModel": "20637008650QT",
"message": "Documento Variants aggiornato per ID existing_variant_id",
"updatedFields": [
"eanCode",
"frameColor",
"lensesColor",
"glassesName",
"mainBrandRef",
"upcCode",
"poster",
"poster2",
"poster3",
"poster4",
"isADV",
"lastUpdate",
"list_size_color_tags",
"list_images",
"size",
"skuReleaseDate",
"skuEndDate",
"advStartDate",
"advEndDate"
]
}
Output (Error)โ
{
"success": false,
"operation": "error",
"documentId": "existing_variant_id",
"skuModel": "UNKNOWN",
"message": "Errore nell'aggiornamento documento Variants: Document not found",
"error": "Document not found"
}
Size Object Structureโ
The function creates a complete size object with all measurements as strings:
{
"size": {
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12"
}
}
Tag Array Structureโ
The function regenerates the list_size_color_tags array with tag IDs:
{
"list_size_color_tags": ["frameColorTagId123", "sizeTagId456"]
}
Tag Creation Process:
- Frame Color Tag: Searches/creates tag with name=frameColor, type="frameColor", group="Frame Color"
- Size Tag: Searches/creates tag with name=size, type="size", group="Size"
- Thread-Safe: Uses mutex synchronization to prevent duplicate tag creation
Date Handlingโ
The function handles timestamp fields with automatic conversion:
- Input: Unix timestamp (number) or current timestamp
- Output: JavaScript Date object
- Validation: Checks if timestamp is valid before conversion
- Fallback: Uses current timestamp if invalid data provided
Related Componentsโ
- Main Function: updateVariantProduct - Main function that calls this helper
- Product Helper: updateProductHelper - Parallel helper for Products collection
- Tag Utilities: tagUtils - Thread-safe tag creation utilities with mutex synchronization to prevent duplicates
Error Handlingโ
The function includes comprehensive error handling:
- Document Not Found: Returns error if variantRef doesn't exist
- Invalid Data: Validates mappedJsonData structure
- Tag Creation Errors: Continues operation even if some tags fail
- Firestore Errors: Catches and logs database operation errors
- Brand Creation Errors: Falls back to empty string if brand operations fail
- Date Conversion Errors: Uses current timestamp as fallback
Performance Considerationsโ
- Thread-Safe Operations: All tag operations use mutex synchronization
- Parallel Tag Creation: Frame color and size tags created simultaneously
- Minimal Database Writes: Only updates changed fields
- Error Isolation: Individual tag failures don't block document update
- Efficient Queries: Uses document ID for direct access
Function Name: updateExistingVariantDocument
Autore: Domenico Cerone Data di creazione: 09/10/2025
Last Reviewer: Domenico Cerone
Trigger: Funzione helper (chiamata da updateVariantProduct)
Purpose: Aggiorna un documento esistente nella collezione 'Variants' di Firestore usando dati JSON mappati aggiornati. Questa funzione gestisce il refresh completo dei campi e la rigenerazione dei tag mantenendo invariati i campi di workflow.
Funzionamento Dettagliatoโ
Questa funzione helper esegue aggiornamenti completi ai documenti Variants esistenti con rigenerazione completa dei tag usando utilitร thread-safe.
1. CARICAMENTO DOCUMENTO ESISTENTEโ
- Riceve
variantRefcome parametro ID documento - Carica documento esistente dalla collezione 'Variants'
- Se NON ESISTE โ errore (non crea nuovi documenti)
- Se ESISTE โ procede con aggiornamento (STEP 2)
2. AGGIORNAMENTO CAMPI E RIGENERAZIONE TAGโ
- Aggiorna solo i campi che provengono dal JSON mappato
- RIGENERA COMPLETAMENTE I TAG (come populateVariantFromSku):
- list_size_color_tags con ID dei tag frameColor e size
- Cerca/crea tag nella collezione Tags usando tagUtils
- Thread-safe per evitare duplicati
- Mantiene tutti i campi di workflow esistenti invariati
- Aggiorna lastUpdate con timestamp corrente
Campi Aggiornati dal JSON Mappatoโ
Campi Base Variante:
eanCodeโ eanCodeframeColorโ frameColorlensesColorโ lensesColorglassesNameโ glassesNamemainBrandRefโ ID brand (cerca/crea nella collezione MainBrands)upcCodeโ upcCodeposterโ posterposter2โ poster2poster3โ poster3poster4โ poster4
Campi Boolean:
isADVโ isADV (convertito da "YES"/"NO" a boolean)
Campi Timestamp:
lastUpdateโ timestamp correnteskuReleaseDateโ skuReleaseDate (se presente)skuEndDateโ skuEndDate (se presente)advStartDateโ advStartDate (se presente)advEndDateโ advEndDate (se presente)
Oggetto Size (tutti i campi come stringhe):
size.bridgeโ bridgesize.frameWidthโ frameWidthsize.lensHeightโ lensHeightsize.lensWidthโ lensWidthsize.sizeโ sizesize.templeLengthโ templeLengthsize.frontHeightโ frontHeightsize.hingeToHingeโ hingeToHingesize.lensCircumferenceโ lensCircumferencesize.lensAngleโ lensAnglesize.phantoscopicAngleโ phantoscopicAngle
Array Speciali (rigenerati dal JSON mappato):
list_size_color_tagsโ [ID tag frameColor, ID tag size] (cerca/crea nella collezione Tags)list_imagesโ list_images (array di oggetti con view e url)
Campi Mantenuti Invariatiโ
Tutti i campi di workflow e configurazione rimangono invariati:
skuModel(identificatore principale)assignedTo,assignmentDate,dataTakenbatch,productRef,catalogOrdersRef,prioritiesModelingloadingId,mainModel,modelPriority,modelViewerUrlmodify_model(oggetto completo)posterNoBackground,primaryFrameColorHex,primaryLensesColorHexpriority,refLogVariant,secondaryFrameColorHex,secondaryLensesColorHexstatus,templeColorurlDE,urlES,urlFR,urlGlobal,urlGlobalComplete, etc.variantCode,list_notes
Funzioni Creazione Tagโ
La funzione usa funzioni specializzate thread-safe per la creazione tag:
Tag Frame Color e Size:
findOrCreateTag()- Crea/trova tag con tipo e gruppo specificati- Frame Color: type="frameColor", group="Frame Color", groupOrder=11
- Size: type="size", group="Size", groupOrder=10
Gestione Brand:
findOrCreateMainBrand()- Crea/trova brand nella collezione MainBrands
Parametri Inputโ
Firma Funzione:
async function updateExistingVariantDocument(variantRef, mappedJsonData, requestId)
Parametri:
variantRef(string, richiesto): ID del documento Variants da aggiornaremappedJsonData(Object, richiesto): Dati JSON mappati aggiornatirequestId(string, richiesto): ID richiesta per logging
Struttura mappedJsonData Attesa:
Questi dati provengono dalla funzione principale dopo aver processato il documento CatalogOrder e scaricato/mappato dati aggiornati dalle API Safilo:
{
"mapped_data": {
"eanCode": "0762753916013",
"frameColor": "BLACK",
"lensesColor": "GREY GRADIENT",
"glassesName": "BOSS 1234/S",
"mainBrandRef": "BOSS EYEWEAR",
"upcCode": "762753916013",
"poster": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg",
"poster2": "https://firebasestorage.googleapis.com/v0/b/.../view_07.jpg",
"poster3": "https://firebasestorage.googleapis.com/v0/b/.../view_02.jpg",
"poster4": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg",
"isADV": "YES",
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12",
"list_images": [
{
"view": "00",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_00.jpg"
},
{
"view": "01",
"url": "https://firebasestorage.googleapis.com/v0/b/.../view_01.jpg"
}
],
"skuReleaseDate": 1640995200000,
"skuEndDate": 1672531200000,
"advStartDate": 1640995200000,
"advEndDate": 1672531200000
}
}
Output (Successo)โ
{
"success": true,
"operation": "update",
"documentId": "id_variant_esistente",
"skuModel": "20637008650QT",
"message": "Documento Variants aggiornato per ID id_variant_esistente",
"updatedFields": [
"eanCode",
"frameColor",
"lensesColor",
"glassesName",
"mainBrandRef",
"upcCode",
"poster",
"poster2",
"poster3",
"poster4",
"isADV",
"lastUpdate",
"list_size_color_tags",
"list_images",
"size",
"skuReleaseDate",
"skuEndDate",
"advStartDate",
"advEndDate"
]
}
Output (Errore)โ
{
"success": false,
"operation": "error",
"documentId": "id_variant_esistente",
"skuModel": "UNKNOWN",
"message": "Errore nell'aggiornamento documento Variants: Document not found",
"error": "Document not found"
}
Struttura Oggetto Sizeโ
La funzione crea un oggetto size completo con tutte le misurazioni come stringhe:
{
"size": {
"bridge": "18",
"frameWidth": "140",
"lensHeight": "45",
"lensWidth": "54",
"size": "54",
"templeLength": "145",
"frontHeight": "45",
"hingeToHinge": "140",
"lensCircumference": "160",
"lensAngle": "6",
"phantoscopicAngle": "12"
}
}
Struttura Array Tagโ
La funzione rigenera l'array list_size_color_tags con ID dei tag:
{
"list_size_color_tags": ["frameColorTagId123", "sizeTagId456"]
}
Processo Creazione Tag:
- Tag Frame Color: Cerca/crea tag con name=frameColor, type="frameColor", group="Frame Color"
- Tag Size: Cerca/crea tag con name=size, type="size", group="Size"
- Thread-Safe: Usa sincronizzazione mutex per prevenire creazione tag duplicati
Gestione Dateโ
La funzione gestisce campi timestamp con conversione automatica:
- Input: Unix timestamp (number) o timestamp corrente
- Output: Oggetto Date JavaScript
- Validazione: Controlla se timestamp รจ valido prima della conversione
- Fallback: Usa timestamp corrente se dati invalidi forniti
Componenti Correlatiโ
- Funzione Principale: updateVariantProduct - Funzione principale che chiama questo helper
- Helper Product: updateProductHelper - Helper parallelo per collezione Variants
- Utilitร Tag: tagUtils - Utilitร creazione tag thread-safe con sincronizzazione mutex per prevenire duplicati
Gestione Erroriโ
La funzione include gestione errori completa:
- Documento Non Trovato: Restituisce errore se variantRef non esiste
- Dati Invalidi: Valida struttura mappedJsonData
- Errori Creazione Tag: Continua operazione anche se alcuni tag falliscono
- Errori Firestore: Cattura e logga errori operazioni database
- Errori Creazione Brand: Fallback a stringa vuota se operazioni brand falliscono
- Errori Conversione Date: Usa timestamp corrente come fallback
Considerazioni Performanceโ
- Operazioni Thread-Safe: Tutte le operazioni tag usano sincronizzazione mutex
- Creazione Tag Parallela: Tag frame color e size creati simultaneamente
- Scritture Database Minimali: Aggiorna solo campi modificati
- Isolamento Errori: Fallimenti tag individuali non bloccano aggiornamento documento
- Query Efficienti: Usa ID documento per accesso diretto